package nju.bishe.weibo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import nju.bishe.weibo.adapter.TweetAdapter;
import nju.bishe.weibo.adapter.TweetArrayAdapter;
import nju.bishe.weibo.data.Tweet;
import nju.bishe.weibo.task.GenericTask;
import nju.bishe.weibo.task.TaskAdapter;
import nju.bishe.weibo.task.TaskListener;
import nju.bishe.weibo.task.TaskParams;
import nju.bishe.weibo.task.TaskResult;
import nju.bishe.weibo.ui.base.TwitterListActivity;
import nju.bishe.weibo.ui.module.MyListView;
import weibo4android.Paging;
import weibo4android.Query;
import weibo4android.QueryResult;
import weibo4android.SearchResult;
import weibo4android.WeiboException;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;

public class SearchResultActivity extends TwitterListActivity implements
                MyListView.OnNeedMoreListener {
        private static final String TAG = "SearchActivity";

        // Views.
        private MyListView mTweetList;

        // State.
        private String mSearchQuery;
        private ArrayList<Tweet> mTweets;
        private TweetArrayAdapter mAdapter;
        private int mNextPage = 1;

        private static class State {
                State(SearchResultActivity activity) {
                        mTweets = activity.mTweets;
                        mNextPage = activity.mNextPage;
                }

                public ArrayList<Tweet> mTweets;
                public int mNextPage;
        }

        // Tasks.
        private GenericTask mSearchTask;
        
        private TaskListener mSearchTaskListener = new TaskAdapter(){
                @Override
                public void onPreExecute(GenericTask task) {
                        animRotate(refreshButton);   
                        if (mNextPage == 1) {
                                updateProgress(getString(R.string.page_status_refreshing));
                        } else {
                                updateProgress(getString(R.string.page_status_refreshing));
                        }
                }

                @Override
                public void onProgressUpdate(GenericTask task, Object param) {
                        draw();
                }

                @Override
                public void onPostExecute(GenericTask task, TaskResult result) {
                        refreshButton.clearAnimation();   
                        if (result == TaskResult.AUTH_ERROR) {
                                logout();
                        } else if (result == TaskResult.OK) {
                                draw();
                        } else {
                                // Do nothing.
                        }

                        updateProgress("");
                }

                @Override
                public String getName() {
                        return "SearchTask";
                }
        };

        @Override
        protected boolean _onCreate(Bundle savedInstanceState) {
                if (super._onCreate(savedInstanceState)){

                        Intent intent = getIntent();
                        // Assume it's SEARCH.
                        // String action = intent.getAction();
                        mSearchQuery = intent.getStringExtra(SearchManager.QUERY);
        
                        if (TextUtils.isEmpty(mSearchQuery)) {
                                mSearchQuery = intent.getData().getLastPathSegment();
                        }
        
                        setHeaderTitle("搜索："+mSearchQuery);
                        setTitle(mSearchQuery);
        
        
                        State state = (State) getLastNonConfigurationInstance();
        
                        if (state != null) {
                                mTweets = state.mTweets;
                                draw();
                        } else {
                                doSearch();
                        }
                        
                        return true;
                }else{
                        return false;
                }
        }

        @Override
        protected int getLayoutId(){
                return R.layout.main;
        }
        
        @Override
        protected void onResume() {
                super.onResume();

                checkIsLogedIn();
        }

        @Override
        public Object onRetainNonConfigurationInstance() {
                return createState();
        }

        private synchronized State createState() {
                return new State(this);
        }

        @Override
        protected void onSaveInstanceState(Bundle outState) {
                super.onSaveInstanceState(outState);
        }

        @Override
        protected void onDestroy() {
                Log.i(TAG, "onDestroy.");

                if (mSearchTask != null
                                && mSearchTask.getStatus() == GenericTask.Status.RUNNING) {
                        mSearchTask.cancel(true);
                }

                super.onDestroy();
        }

        // UI helpers.

        private void updateProgress(String progress) {
                mProgressText.setText(progress);
        }

        private void draw() {
                mAdapter.refresh(mTweets);
        }

        private void doSearch() {
                Log.i(TAG, "Attempting search.");
                
                if (mSearchTask != null && mSearchTask.getStatus() == GenericTask.Status.RUNNING){
                        return;
                }else{
                        mSearchTask = new SearchTask();
                        mSearchTask.setListener(mSearchTaskListener);
                        mSearchTask.execute();
                }
        }

        private class SearchTask extends GenericTask {
        
                ArrayList<Tweet> mTweets = new ArrayList<Tweet>();

                @Override
                protected TaskResult _doInBackground(TaskParams...params) {
                        List<weibo4android.Status> results;
                        QueryResult result=null;
                        
//TODO
                        try {
                                Query query = new Query(mSearchQuery);
                                query.setPage(mNextPage);
                                results =  getApi().getTrendStatus(mSearchQuery,new Paging(1));//.search(mSearchQuery, mNextPage);
                        } catch (WeiboException e) {
                                Log.e(TAG, e.getMessage(), e);
                                return TaskResult.IO_ERROR;
                        }

                        HashSet<String> imageUrls = new HashSet<String>();
//
                        for (weibo4android.Status status :results) {
                                if (isCancelled()) {
                                        return TaskResult.CANCELLED;
                                }

                                Tweet tweet;

                                tweet = Tweet.create(status);
                                mTweets.add(tweet);
                                imageUrls.add(tweet.profileImageUrl);

                                if (isCancelled()) {
                                        return TaskResult.CANCELLED;
                                }
                        }

                        addTweets(mTweets);
                        return TaskResult.OK;
                }
        }
        
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
                return super.onCreateOptionsMenu(menu);
        }

        @Override
        public void needMore() {
                if (!isLastPage()) {
                        doSearch();
                }
        }

        public boolean isLastPage() {
                return mNextPage == -1;
        }

        @Override
        protected void adapterRefresh() {
                mAdapter.refresh(mTweets);
        }

        private synchronized void addTweets(ArrayList<Tweet> tweets) {
                if (tweets.size() == 0) {
                        mNextPage = -1;
                        return;
                }

                mTweets.addAll(tweets);

                ++mNextPage;
        }

        @Override
        protected String getActivityTitle() {
                return mSearchQuery;
        }

        @Override
        protected Tweet getContextItemTweet(int position) {
                return (Tweet)mAdapter.getItem(position);
        }

        @Override
        protected TweetAdapter getTweetAdapter() {
                return mAdapter;
        }

        @Override
        protected ListView getTweetList() {
                return mTweetList;
        }


        protected void updateTweet(Tweet tweet) {
                // TODO Simple and stupid implementation
                for (Tweet t : mTweets){
                        if (t.id.equals(tweet.id)){
                                t.favorited = tweet.favorited;
                                break;
                        }
                }
        }

        @Override
        protected boolean useBasicMenu() {
                return true;
        }

        @Override
        protected void setupState() {
                mTweets = new ArrayList<Tweet>();
                mTweetList = (MyListView) findViewById(R.id.tweet_list);
                mAdapter = new TweetArrayAdapter(this);
                mTweetList.setAdapter(mAdapter);
                mTweetList.setOnNeedMoreListener(this);         
        }

        @Override
        public void doRetrieve() {
                doSearch();
        }


}
